package com.finalhomework.dms.controller;


import com.finalhomework.dms.dao.AdminRepository;
import com.finalhomework.dms.dao.StudentRepository;
import com.finalhomework.dms.entities.Admin;
import com.finalhomework.dms.entities.Students;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {

    @Autowired
    AdminRepository adminRepository;
    @Autowired
    StudentRepository studentRepository;
    @PostMapping("/user/login")
    public String login(


            @RequestParam("username") String username,
            @RequestParam("password") String password,
            Model model, HttpSession session){
        List<Admin> adminAll = adminRepository.findAll();
        for(Admin admin : adminAll){
            if(username.equals(admin.getUserName())&&password.equals(admin.getPassword())){
                session.setAttribute("loginUser",username);
                return "redirect:/page";
            }
        }


            model.addAttribute("msg","用户名或密码错误");
            return "index";

    }

    @PostMapping("/user/stuLogin")
    public String stuLogin(


            @RequestParam("username") long username,
            @RequestParam("password") String password,
            Model model, HttpSession session){

        List<Students> studentAll = studentRepository.findAll();
        for(Students students : studentAll){
            if(username==(students.getNumber())&&password.equals(students.getPaw())){
                session.setAttribute("loginUser",username);
                return "redirect:/stu_page";
            }
        }


        model.addAttribute("msg","用户名或密码错误");
        return "stuIndex";

    }

    @RequestMapping("/user/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/";
    }

}
